using UnityEngine;

public class DartController : MonoBehaviour
{
    [Header("引用")]
    public GameObject dartPrefab;
    public Transform launchPoint;

    [Header("参数")]
    public float maxChargePower = 100f; // 最大蓄力值
    public float chargeSpeed = 50f;     // 蓄力增长速度
    public float minLaunchForce = 5f;   // 最小发射力
    public float maxLaunchForce = 20f;  // 最大发射力

    private float _currentCharge = 0f;  // 当前蓄力值（私有字段）
    private bool isCharging = false;    // 是否正在蓄力

    private void Update()
    {
        HandleInput();
    }

    private void HandleInput()
    {
        // 鼠标左键按下开始蓄力
        if (Input.GetMouseButtonDown(0))
        {
            StartCharging();
        }

        // 鼠标左键按住持续蓄力
        if (Input.GetMouseButton(0) && isCharging)
        {
            Charge();
        }

        // 鼠标左键释放发射飞镖
        if (Input.GetMouseButtonUp(0) && isCharging)
        {
            Fire();
        }
    }

    private void StartCharging()
    {
        isCharging = true;
        _currentCharge = 0f;
    }

    private void Charge()
    {
        // 增加蓄力值，限制不超过最大值
        _currentCharge += chargeSpeed * Time.deltaTime;
        _currentCharge = Mathf.Clamp(_currentCharge, 0f, maxChargePower);
    }

    private void Fire()
    {
        isCharging = false;

        // 计算发射力（根据蓄力百分比）
        float chargePercentage = _currentCharge / maxChargePower;
        float launchForce = Mathf.Lerp(minLaunchForce, maxLaunchForce, chargePercentage);

        // 实例化飞镖
        GameObject dart = Instantiate(dartPrefab, launchPoint.position, launchPoint.rotation);

        // 获取飞镖的刚体组件
        Rigidbody dartRb = dart.GetComponent<Rigidbody>();
        if (dartRb == null)
        {
            Debug.LogError("飞镖预制体缺少Rigidbody组件！");
            return;
        }

        // 应用发射力
        dartRb.AddForce(launchPoint.forward * launchForce, ForceMode.Impulse);

        // 重置蓄力
        _currentCharge = 0f;
    }

    // 供ChargeBar脚本获取当前蓄力值（公有属性）
    public float CurrentCharge
    {
        get { return _currentCharge; }
    }
}